'use strict';
const Service = require('egg').Service;
const md5 = require('md5');

class PcenterService extends Service {
  async centerPost(path, data = {}) {
    const { ctx, app } = this;
    const pcenterConf = app.config.pcenter;
    const url = `${pcenterConf.host}${path}`;
    const t = (new Date()).valueOf();
    const token = this.makeToken(pcenterConf.pid, pcenterConf.secret, t);
    try {
      const { data: res } = await ctx.curlPost(url, data, {
        headers: {
          Authorization: token,
          pid: pcenterConf.pid,
        },
      });
      if (res.code !== 'SUCCESS') {
        ctx.throwBizError(res.msg);
      }
      return res.data;
    } catch (error) {
      ctx.throwSysError('项目中心请求失败', error);
    }
  }
  async centerGet(path, params = {}) {
    const { ctx, app } = this;
    const pcenterConf = app.config.pcenter;
    const url = `${pcenterConf.host}${path}`;
    const t = (new Date()).valueOf();
    const token = this.makeToken(pcenterConf.pid, pcenterConf.secret, t);
    try {
      const { data: res } = await ctx.curlGet(url, params, {
        headers: {
          Authorization: token,
          pid: pcenterConf.pid,
        },
      });
      if (res.code !== 'SUCCESS') {
        ctx.throwBizError(res.msg);
      }
      return res.data;
    } catch (error) {
      ctx.throwSysError('项目中心请求失败', error);
    }
  }
  // 签名方法
  makeToken(pid, secret, t) {
    const sign = md5(pid + secret + t);
    return `${pid}.${sign}.${t}`;
  }
}

module.exports = PcenterService;
